#include "myorderspanel.h"
#include <QTableWidget>
#include <QPushButton>
#include <QLabel>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QMessageBox> // For potential messages
#include <QDateTime>   // For time conversion

// Include C backend headers
extern "C" {
#include "../backend/order.h"
#include "../backend/drink.h" // Needed for drink lookups
}

MyOrdersPanel::MyOrdersPanel(QWidget *parent) :
    QDialog(parent),
    orderListHead(nullptr), // Initialize pointers
    drinkListHead(nullptr)
{
    setWindowFlags(windowFlags() | Qt::Dialog);
    setModal(true);
    setAutoFillBackground(true); // 防止透明
    setupUi();
    // Initial load can be triggered externally after setting user ID
}

MyOrdersPanel::~MyOrdersPanel()
{
    // Free lists if they happen to hold data (though they should be freed in loadOrders)
    if (orderListHead) {
        free_all_orders(orderListHead);
    }
    if (drinkListHead) {
        free_all_drinks(drinkListHead);
    }
}

void MyOrdersPanel::setupUi()
{
    // Table View for Orders
    orderTable = new QTableWidget();
    orderTable->setColumnCount(6); // OrderID, DrinkName, Quantity, TotalPrice, OrderTime, Status
    orderTable->setHorizontalHeaderLabels(QStringList() << "订单ID" << "商品名称" << "数量" << "总价" << "下单时间" << "状态");
    orderTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    orderTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::ResizeToContents); // Resize ID column
    orderTable->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); // Resize Quantity column
    orderTable->horizontalHeader()->setSectionResizeMode(3, QHeaderView::ResizeToContents); // Resize Price column
    orderTable->horizontalHeader()->setSectionResizeMode(5, QHeaderView::ResizeToContents); // Resize Status column
    orderTable->setSelectionBehavior(QAbstractItemView::SelectRows);
    orderTable->setSelectionMode(QAbstractItemView::SingleSelection);
    orderTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // Status Label
    statusLabel = new QLabel("请先加载订单...");

    // Refresh Button
    refreshButton = new QPushButton("🔄 刷新");

    // Layouts
    QHBoxLayout *bottomLayout = new QHBoxLayout();
    bottomLayout->addWidget(statusLabel);
    bottomLayout->addStretch();
    bottomLayout->addWidget(refreshButton);

    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->addWidget(orderTable);
    mainLayout->addLayout(bottomLayout);

    // Connections
    connect(refreshButton, &QPushButton::clicked, this, &MyOrdersPanel::refreshOrders);
}

// Implementation for loadOrders, populateTable, clearTable, refreshOrders
void MyOrdersPanel::loadOrders(int userId) {
    currentUserId = userId; // Store the user ID

    // Free any previously loaded lists (important for refresh)
    if (orderListHead) {
        free_all_orders(orderListHead);
        orderListHead = nullptr;
    }
    if (drinkListHead) {
        free_all_drinks(drinkListHead);
        drinkListHead = nullptr;
    }

    // Load all orders and all drinks from backend
    int orderCount = load_orders("orders.dat", &orderListHead);
    int drinkCount = load_drinks("drinks.dat", &drinkListHead); // Need drinks for name/price lookup

    if (orderCount < 0 || drinkCount < 0) { // Assuming load functions return -1 on file error
         QMessageBox::critical(this, "加载错误", "无法加载订单或饮品数据文件！");
         statusLabel->setText("加载数据失败");
         // Ensure lists are null if loading failed
         if(orderListHead) free_all_orders(orderListHead); orderListHead = nullptr;
         if(drinkListHead) free_all_drinks(drinkListHead); drinkListHead = nullptr;
         clearTable();
         return;
    }

    populateTable(); // Fill the table using the loaded data

    // Update status label (count only *this* user's orders in populateTable if needed)
    // statusLabel->setText(QString("共 %1 条订单").arg(orderTable->rowCount())); // Updated in populateTable

    // Free the C linked lists after populating the table
    if (orderListHead) {
        free_all_orders(orderListHead);
        orderListHead = nullptr;
    }
    if (drinkListHead) {
        free_all_drinks(drinkListHead);
        drinkListHead = nullptr;
    }
}

void MyOrdersPanel::populateTable() {
    clearTable();
    int userOrderCount = 0;

    OrderNode* currentOrder = orderListHead;
    while (currentOrder != nullptr) {
        // Filter orders for the current user
        if (currentOrder->data.user_id == currentUserId) {
            userOrderCount++;
            int row = orderTable->rowCount();
            orderTable->insertRow(row);

            // 1. Order ID
            orderTable->setItem(row, 0, new QTableWidgetItem(QString::number(currentOrder->data.id)));

            // 2. Drink Name & 3. Total Price (Requires lookup)
            QString drinkName = "未知商品";
            float totalPrice = 0.0;
            DrinkNode* drinkNode = find_drink_by_id(drinkListHead, currentOrder->data.drink_id);
            if (drinkNode) {
                drinkName = QString::fromUtf8(drinkNode->data.name);
                totalPrice = currentOrder->data.quantity * drinkNode->data.price;
            } else {
                 drinkName = QString("商品ID:%1 (已失效)").arg(currentOrder->data.drink_id);
            }
            orderTable->setItem(row, 1, new QTableWidgetItem(drinkName));
            orderTable->setItem(row, 3, new QTableWidgetItem(QString::number(totalPrice, 'f', 2))); // Total Price

            // 4. Quantity
            orderTable->setItem(row, 2, new QTableWidgetItem(QString::number(currentOrder->data.quantity)));

            // 5. Order Time
            QDateTime dt = QDateTime::fromSecsSinceEpoch(currentOrder->data.order_time);
            orderTable->setItem(row, 4, new QTableWidgetItem(dt.toString("yyyy-MM-dd hh:mm")));

            // 6. Status
            QString statusText;
            switch (currentOrder->data.status) {
                case ORDER_STATUS_PENDING: statusText = "待处理"; break;
                case ORDER_STATUS_FINISHED: statusText = "已完成"; break;
                case ORDER_STATUS_CANCELED: statusText = "已取消"; break;
                default: statusText = "未知"; break;
            }
            orderTable->setItem(row, 5, new QTableWidgetItem(statusText));

            // Store order ID in the first column's item data (optional, for future use)
            orderTable->item(row, 0)->setData(Qt::UserRole, currentOrder->data.id);
        }
        currentOrder = currentOrder->next;
    }
     statusLabel->setText(QString("共 %1 条订单").arg(userOrderCount));
}

void MyOrdersPanel::clearTable() {
     orderTable->clearContents();
     orderTable->setRowCount(0);
}

void MyOrdersPanel::refreshOrders() {
    if (currentUserId != -1) {
        loadOrders(currentUserId);
    } else {
        QMessageBox::warning(this, "错误", "未设置当前用户ID，无法刷新订单。");
    }
}